﻿namespace CRM.DataAccess.DAOs
{
    using System.Collections.Generic;
    using System.Data.Entity;
    using CRM.DataAccess.Entities;
    using System.Linq;
    

    public class ItemDAO : DbContext
    {
        public ItemDAO()
            : base("name=Entities")
        {
        }

        public DbSet<ITEM_DETAILS> ITEM_DETAILS { get; set; }
        public DbSet<ITEM> ITEMS { get; set; }
        public DbSet<ITEM_DETAIL> ITEM_DETAIL { get; set; }

        //Delete Item
        public int DeleteItem(long itemID)
        {
            var trans = this.Database.BeginTransaction();
            try
            {
                ITEMS.RemoveRange(ITEMS.Where(x=>x.ID==itemID));
                this.SaveChanges();
                ITEM_DETAIL.RemoveRange(ITEM_DETAIL.Where(x=>x.ITEM_ID==itemID));
                SaveChanges();
                trans.Commit();
                return 1;
            }
            catch
            {
                trans.Rollback();
                return -1;
            }
        }
        //Add new item
        public int AddNewItem(ITEM item, List<ITEM_DETAIL> itemDetails)
        {
            var trans = this.Database.BeginTransaction();
            try
            {
                this.ITEMS.Add(item);
                this.SaveChanges();
                foreach (ITEM_DETAIL idetail in itemDetails)
                {
                    idetail.ITEM_ID = item.ID;
                    this.ITEM_DETAIL.Add(idetail); 
                    this.SaveChanges();

                }
                trans.Commit();
                return 1;
            }
            catch  
            {
                trans.Rollback();
                return -1;
            }


        }
        //Get Item by ID
        public ITEM GetItemByID(long? ID)
        {
            try
            {
                var Query = (from i in ITEMS
                            where i.ID == ID
                            select i).FirstOrDefault<ITEM>();
                return Query as ITEM;
            }
            catch
            {
                return null;
            }
        }
        //Get  List item detail by Item_ID
        public List<ITEM_DETAILS> GetListItemDetailByItemID(long? itemID)
        {
            try
            {
                if (itemID != null)
                {
                    var Query = from i in ITEMS
                                from id in ITEM_DETAILS
                                where i.ID == itemID && i.ID == id.ITEM_ID
                                select id;
                    List<ITEM_DETAILS> items = Query.AsNoTracking().ToList();
                    if (items.Count > 0)
                        return items;
                }
                return null;
            }
            catch
            {
                return null;
            }
        }
    }
}
